"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : autocommit
Case Name   : 关闭自动提交，执行匿名块，提交，新开会话查询
Create At   : 2023/01/17
@zou_jialiang0501162244
Description :
    1、会话1：关闭自动提交，执行包含DDL、DML语句的匿名块，commit
    2、会话2：会话1执行提交前后查询数据
    3、关闭自动提交，执行含有DDL,DML语句的匿名块，查询，回滚
    4、清理环境
Expect      :
    1、成功
    2、表不存在，会话1提交后查询1条数据
    3、查询1条数据 1 abort，回滚后查询报错
    4、成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class TestAutocommit(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.tb1_name = 't_autocommit_0039_1'
        self.tb2_name = 't_autocommit_0039_2'
        self.db_name = 'db_autocommit_0039'
        self.log.info("-----预置兼容B库-----")
        preset_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} dbcompatibility 'B';"
        preset_db_res = self.pri_sh.execut_db_sql(preset_db)
        self.log.info(preset_db_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, preset_db_res,
                      f"创建兼容B库失败")

    def test_autocommit(self):
        text1 = '-----step1:会话1：关闭自动提交，执行包含DDL、DML语句的' \
                '匿名块，commit;expect:成功-----'
        self.log.info(text1)
        sql1 = f'''set autocommit to false;
        declare
        begin
        drop table if exists {self.tb1_name} cascade;
        create table {self.tb1_name}(sk integer, 
        id char(16), name varchar(20), sq_ft integer);
        insert into {self.tb1_name} values(008,'sk1','tt',3332);
        end;
        select pg_sleep(3);
        commit;'''
        session1 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql1, '', self.db_name))
        session1.setDaemon(True)
        session1.start()
        time.sleep(2)

        text2 = '-----step2:会话2：会话1执行提交前后查询数据;' \
                'expect:表不存在，会话1提交后查询1条数据-----'
        self.log.info(text2)
        sql2 = f"select tablename from pg_tables " \
               f"where tablename = '{self.tb1_name}';" \
               f"select pg_sleep(3);" \
               f"select * from {self.tb1_name} where sk = 8;"
        session2 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql2, '', self.db_name))
        session2.setDaemon(True)
        session2.start()
        session1.join(10)
        session2.join(10)
        res1 = session1.get_result()
        self.log.info(f'session1_results:\n {res1}')
        res2 = session2.get_result()
        self.log.info(f'session2_results:\n {res2}')
        self.assertIn('SET', res1, f"关闭自动提交失败: {text1}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, res1, f"执行失败: {text1}")
        self.assertIn('0 rows', res2.splitlines()[2], f"执行失败: {text2}")
        self.assertIn('8 | sk1              | tt   |  3332', res2,
                      f"执行失败: {text2}")

        text3 = '-----step3:关闭自动提交，执行含有DDL,DML语句的匿名块，查询，回滚;' \
                'expect:查询1条数据 1 abort，回滚后查询报错-----'
        self.log.info(text3)
        sql = f'''set autocommit to false;
        do \$\$ declare
        begin
        drop table if exists {self.tb2_name} cascade;
        create table {self.tb2_name}(sk integer, 
        id char(16), name varchar(20), sq_ft integer);
        insert into {self.tb2_name} values(1, 'abort', 'to', 1234);
        end \$\$;
        select * from {self.tb2_name};
        rollback;
        select * from {self.tb2_name};
        abort;'''
        res = self.pri_sh.execut_db_sql(sql, dbname=self.db_name)
        self.log.info(res)
        self.assertEqual(res.count(self.constant.ROLLBACK_MSG), 2,
                         f"执行失败:{text3}")
        self.assertIn('1 | abort            | to   |  1234', res,
                      f"执行失败:{text3}")
        self.assertIn(self.constant.ANONYMOUS_BLOCK_EXECUTE_SUCCESS_MSG, res,
                      f"执行失败:{text3}")
        self.assertIn(f'ERROR:  relation', res, f"执行失败:{text3}")

    def tearDown(self):
        text4 = '-----step4:清理环境 expect:成功-----'
        self.log.info(text4)
        drop_db_res = self.pri_sh.execut_db_sql(
            f"drop database if exists {self.db_name};")
        self.log.info(drop_db_res)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_db_res,
                      f"执行失败: {text4}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
